package com.tudou.searchcontrol.web;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tudou.searchcontrol.model.Album;
import com.tudou.searchcontrol.model.PageInfo;
import com.tudou.searchcontrol.model.TudouM;
import com.tudou.searchcontrol.service.IAlbumService;
import com.tudou.searchcontrol.service.ITudouMService;
import com.tudou.searchcontrol.utils.ReadPage;

@Controller
@RequestMapping("/demo/*")
public class TudouMAction extends BaseAction{

	@Autowired
	private ITudouMService tudouMService;
	
	private static final ObjectMapper objectMapper = new ObjectMapper();
	
	@RequestMapping("list")
	public String list(HttpServletRequest request, HttpServletResponse response, ModelMap model,PageInfo pageInfo){
		if(pageInfo == null){
		  pageInfo = new PageInfo();
		}
		List<TudouM> list = tudouMService.getAlbumList(pageInfo);
		model.put("albumList", list);
		return "/demo/albumList";
	}

	@RequestMapping("loadPage")
	public void loadPage(HttpServletRequest request, HttpServletResponse response, ModelMap model,PageInfo pageInfo){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			List<TudouM> list = tudouMService.getAlbumList(pageInfo);
			
	        String bodystr = objectMapper.writeValueAsString(list);
			out.print(bodystr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
//	@RequestMapping("readPage")
//	public String readPage(HttpServletRequest request, HttpServletResponse response, ModelMap model){
//		ReadPage readPage = new ReadPage(request,response);
//		
//		List<String> albumList = new ArrayList<String>();
//		for(int i=0;i<30;i++){
//			String xmlUrl = "http://export.tudou.com/new_baidu_album/m_page"+i+"_album.xml";
//			List<Album> list  = albumService.getAlbumList(xmlUrl);
//			String url = "http://show.soku.com/v?keyword=";
//			for(Album album:list){
//				String title = "";
//				try {
//					title = URLEncoder.encode(album.getTitle(),"UTF-8");
//				} catch (UnsupportedEncodingException e) {
//					e.printStackTrace();
//				}
//				String pageInfo = readPage.include(url+title,null);
//				boolean istudou = albumService.getImgSrc(pageInfo);
//				if(!istudou){
//					albumList.add(album.getTitle());
////					System.out.println(album.getTitle());
//				}
//			}
//		}
//		
//		try{
//			System.out.println("---start----");
//			FileWriter fw=new FileWriter(new File("E:/albumList.txt"));
//			BufferedWriter  bw=new BufferedWriter(fw);
//			for(String obj:albumList){
//				bw.write(obj+"\r\n");
//			}
//			bw.close();
//	        fw.close();
//		}catch (Exception e) {
//			System.out.println(e);
//	    }
//		
//		System.out.println("---end----");
//		return "/album/albumList";
//	}
	
	@RequestMapping("readPageDatabase")
	public String readPageDatabase(HttpServletRequest request, HttpServletResponse response, ModelMap model){

		for(int i=0;i<30;i++){
			String xmlUrl = "http://export.tudou.com/new_baidu_album/m_page"+i+"_album.xml";
			List<TudouM> list  = tudouMService.getTudouMList(xmlUrl);
			for(TudouM tudouM:list){
				tudouMService.saveOrUpdateTudouM(tudouM);
			}
			System.out.println("==="+i);
		}
		
		
		return "/demo/albumList";
	}
	
	@RequestMapping("view")
	public String view(HttpServletRequest request, HttpServletResponse response, ModelMap model,Long id){
		TudouM tudouM = tudouMService.getTudouMById(id);
		model.put("album",tudouM);
		return "/demo/albumView";
	}
	
	@RequestMapping("play")
	public String play(HttpServletRequest request, HttpServletResponse response, ModelMap model,Integer type,String url){
		
		
		String playUrl = getTudouVideoContent(request,response,url);
		try {
			Map<String, Object> map = objectMapper.readValue(playUrl, Map.class);
			Map<String, Object> map1 = (Map<String, Object>)map.get("repasteInfo");
			Map<String, Object> map2 = (Map<String, Object>)map1.get("itemInfo");
			playUrl = (String)map2.get("outerPlayerUrl");
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(playUrl.indexOf("autoPlay=true")<0){
			playUrl = playUrl.substring(0,playUrl.lastIndexOf("/"))+"/&autoPlay=true"+playUrl.substring(playUrl.lastIndexOf("/"));
		}
		model.put("playUrl",playUrl);
		return "/demo/paly";
	}
	
	private String getTudouVideoContent(HttpServletRequest request, HttpServletResponse response,String vidioUrl){
		ReadPage readPage = new ReadPage(request,response);
//		String url = "http://my.tv.sohu.com/u/vw/30971244";
		String url = "http://api.tudou.com/v3/gw?method=repaste.info.get&appKey=b8005c8e0c2d1085&url="+vidioUrl;
		String pageInfo = readPage.include(url,"utf-8");
		return pageInfo;
	}
	

}
